package com.jumi.microservice.controller.order;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jumi.microservice.common.base.BaseController;
import com.jumi.microservice.common.base.dto.BaseResponse;
import com.jumi.microservice.common.base.dto.ResponseResult;
import com.jumi.microservice.common.page.TableDataInfo;
import com.jumi.microservice.common.utils.IpUtil;
import com.jumi.microservice.constant.compensation.AfterSaleStatusEnum;
import com.jumi.microservice.dto.PaymentRequest;
import com.jumi.microservice.dto.WaitCommentRequest;
import com.jumi.microservice.dto.WaitCommentResponse;
import com.jumi.microservice.dto.order.*;
import com.jumi.microservice.dto.pay.OrderPayListResponse;
import com.jumi.microservice.dto.shoppingcart.ShoppingCartListRequest;
import com.jumi.microservice.dto.shoppingcart.ShoppingCartRequest;
import com.jumi.microservice.dto.shoppingcart.ShoppingCartResponse;
import com.jumi.microservice.entity.UserOrder;
import com.jumi.microservice.mapper.UserOrderMapper;
import com.jumi.microservice.service.IOrderDubboService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.client.producer.SendStatus;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author Dirk
 * @Date 2020-07-07 18:16
 */
@RestController
@RequestMapping("/api/order")
@Api(tags = {"C-订单前端接口"})
@RefreshScope
public class OrderController extends BaseController {

    @DubboReference
    private IOrderDubboService orderDubboService;
    @Resource
    UserOrderMapper userOrderMapper;

    @PostMapping("/confirm/goods")
    @ApiOperation("确认订单页列表")
    public ResponseResult<ConfirmOrderResponse> confirmOrder(@RequestBody CreateOrderRequest createOrderRequest) {
        createOrderRequest.setUid(getApiUserId().longValue());
        return success(orderDubboService.confirmOrder(createOrderRequest));
    }

    @PostMapping("/create")
    @ApiOperation("创建提交订单")
    public ResponseResult<CreateOrderResponse> createOrder(@RequestBody CreateOrderRequest createOrderRequest, HttpServletRequest httpServletRequest) {
        createOrderRequest.setUid(getApiUserId().longValue());
        createOrderRequest.setClientIp(IpUtil.getClientIp(httpServletRequest));
        String loginClient = httpServletRequest.getHeader("loginClient");
        createOrderRequest.setPlatformType(getPlatformType(loginClient));
        return success(orderDubboService.createOrder(createOrderRequest));
    }

    /**
     * 获取请求平台
     * TODO 整合到baseController中
     *
     * @param loginClient
     * @return
     */
    private Byte getPlatformType(String loginClient) {
        if (ObjectUtils.isEmpty(loginClient)) {
            return new Byte("0");
        } else if ("android".equals(loginClient)) {
            return new Byte("1");
        } else if ("ios".equals(loginClient)) {
            return new Byte("2");
        } else if ("h5".equals(loginClient)) {
            return new Byte("3");
        } else if ("xcx".equals(loginClient)) {
            return new Byte("4");
        } else {
            return new Byte("0");
        }
    }

    @PostMapping("/payment")
    @ApiOperation("支付订单")
    public ResponseResult<BaseResponse> payment(PaymentRequest paymentRequest, HttpServletRequest httpServletRequest) {
        paymentRequest.setClientIp(IpUtil.getClientIp(httpServletRequest));
        paymentRequest.setUid(getApiUserId().longValue());
        paymentRequest.setSubject("聚米团");
        return success(orderDubboService.payment(paymentRequest));
    }

    @PostMapping("/cancel")
    @ApiOperation("取消订单")
    public ResponseResult<Boolean> cancel(OrderInfoRequest orderInfoRequest) {
        orderInfoRequest.setUid(getApiUserId().longValue());
        return success(orderDubboService.cancel(orderInfoRequest));
    }

    @PostMapping("/shopping-cart/add")
    @ApiOperation("加入、减少购物车")
    public ResponseResult<Boolean> addShoppingCart(ShoppingCartRequest request) {
        request.setUid(getApiUserId().longValue());
        return success(orderDubboService.addShoppingCart(request));
    }

    @PostMapping("/shopping-cart/add-list")
    @ApiOperation("批量加入购物车")
    public ResponseResult<Boolean> addShoppingCart(@RequestBody ShoppingCartListRequest request) {
        request.setUid(getApiUserId().longValue());
        return success(orderDubboService.addShoppingCart(request));
    }

    @PostMapping("/shopping-cart/list")
    @ApiOperation("购物车列表")
    public ResponseResult<ShoppingCartResponse> getShoppingCart() {
        return success(orderDubboService.getShoppingCart(getApiUserId()));
    }

    @PostMapping("/shopping-cart/delete")
    @ApiOperation("批量删除")
    public ResponseResult<Boolean> deleteShoppingCart(@RequestBody ShoppingCartListRequest request) {
        request.setUid(getApiUserId().longValue());
        return success(orderDubboService.deleteShoppingCart(request));
    }

    @PostMapping("/shopping-cart/update")
    @ApiOperation("修改购物车商品规格")
    public ResponseResult<Boolean> changeShoppingCartSku(ShoppingCartRequest request) {
        request.setUid(getApiUserId().longValue());
        return success(orderDubboService.changeShoppingCartSku(request));
    }

    @PostMapping("/info/list")
    @ApiOperation("我的订单列表")
    public TableDataInfo<OrderResponse> getOrderInfo(OrderInfoRequest request) {
        request.setUid(getApiUserId().longValue());
        return orderDubboService.getOrderInfoPage(request);
    }

    @PostMapping("/info/search")
    @ApiOperation("搜索我的订单列表")
    public TableDataInfo<OrderResponse> getOrderInfoSearch(OrderInfoRequest request) {
        request.setUid(getApiUserId().longValue());
        return (orderDubboService.getOrderInfoSearch(request));
    }

    @PostMapping("/confirm")
    @ApiOperation("确认收货")
    public ResponseResult<Boolean> confirmReceipt(OrderInfoRequest request) {
        request.setUid(getApiUserId().longValue());
        return success(orderDubboService.confirmReceipt(request));
    }

    @PostMapping("/delete")
    @ApiOperation("删除订单")
    public ResponseResult<Boolean> deleteOrder(OrderInfoRequest request) {
        request.setUid(getApiUserId().longValue());
        return success(orderDubboService.deleteOrder(request));
    }

    @Resource
    private RocketMQTemplate rocketMQTemplate;

    @PostMapping("/rocket-mq/send")
    @ApiOperation("模拟发送订单消息")
    public ResponseResult<Boolean> sendRocketMqMessage(OrderMessage orderMessage) {
        SendResult sendResult = rocketMQTemplate.syncSend("order", MessageBuilder.withPayload(orderMessage).build());
        return success(SendStatus.SEND_OK.equals(sendResult.getSendStatus()));
    }

    @PostMapping("/waitCommentOrder")
    @ApiOperation("待评价订单")
    public TableDataInfo<WaitCommentResponse> waitCommentList(WaitCommentRequest request) {
        Long uid = getApiUserId().longValue();
        request.setUid(uid);
        return orderDubboService.waitCommentList(request);
    }

    /**
     * 用户待评价订单数量
     *
     * @param uid
     * @return
     */
    @GetMapping("/waitCommentCount")
    public Integer waitCommentCount(Long uid) {
        return orderDubboService.waitCommentCount(uid);
    }


    /**
     * 售后状态字典
     *
     * @return
     */
    @GetMapping("/afterSaleStatus")
    @ApiOperation("订单售后状态字典")
    public Map<Object, Object> afterSaleStatusDic() {
        AfterSaleStatusEnum[] afterSaleStatusEnums = AfterSaleStatusEnum.values();
        return Arrays.asList(afterSaleStatusEnums).stream()
                .collect(Collectors.toMap(AfterSaleStatusEnum::getCode, AfterSaleStatusEnum::getMsg));
    }

    @PostMapping("/getPayType")
    @ApiOperation("获取支付类型:")
    public ResponseResult<List<OrderPayListResponse>> getPayType(@ApiParam(name = "clientType", value = "客户端类型：1、app 2、H5 3、小程序", example = "1") @RequestParam("clientType") Integer clientType) {
        return orderDubboService.getPayType(clientType);
    }

    @GetMapping("/remainSeconds")
    @ApiOperation("待支付剩余秒数")
    public ResponseResult<RemainSecondsResponse> remainSeconds(RemainSecondsRequest request) {
        QueryWrapper<UserOrder> queryWrapper = new QueryWrapper<>();
        if (request.getOrderNo() != null && !request.getOrderNo().trim().isEmpty()) {
            queryWrapper.eq("order_no", request.getOrderNo()).last("limit 1");
        } else {
            queryWrapper.eq("pay_no", request.getPayNo()).last("limit 1");
        }
        UserOrder userOrder = userOrderMapper.selectOne(queryWrapper);
        RemainSecondsResponse remainSecondsResponse = new RemainSecondsResponse();
        if (!ObjectUtils.isEmpty(userOrder)) {
            long seconds = (userOrder.getFailureTime().getTime() - System.currentTimeMillis()) / 1000;
            remainSecondsResponse.setRemainSeconds(seconds > 0 ? seconds : 0L);
        } else {
            remainSecondsResponse.setRemainSeconds(0L);
        }
        return success(remainSecondsResponse);
    }
}
